<?php
/*
 * @param author feyeen
 */

namespace services\models;

use Yii;
use yii\data\Pagination;
use common\models\OrderExpress as OrderAddress;
use common\models\OrderInfoHistory;     //历史订单
use common\models\OrderGoodsHistory;    //历史订单商品表
use common\models\OrderExpressHistory;

class OrderInfoDetail extends OrderInfo
{
    public static $STATUS_COMMENT_NO    = 0;          //评论状态 0未评论 1已评论
    public static $STATUS_COMMENT_OK    = 1;          //评论状态 0未评论 1已评论
    public static $STATUS_IN_KEY        = array(2,3,4);//分组
    public static $STATUS_ORDERSTR_OK   = '待评价';
    public static $EXPRESS_INFO         = array(
        1=>'韵达快递',
        4=>'邮政快递',
    );
    public static $EXPRESS_EMS          = 4;
    public static $EXPRESS_RHYME        = 1;
    public static $LIKETRY_DIFF         = 20000000;

    public function scenarios(){

        return parent::scenarios();
    }

    //查询订单信心
    public function getOrderInfo(&$param){
        if(!is_array($param))
             return false;
        $historyId          = 0;
        //查询3个月之前的订单
        $orderInfo          = self::find()->where($param)->joinWith('lgistics',true,'LEFT JOIN')->one();

        //若果没有3个月之后的订单  查询3个月之后的订单
        if(empty($orderInfo)){
            $orderInfo      = OrderInfoHistory::find()->where($param)->joinWith('lgistics',true,'LEFT JOIN')->one();
            $historyId      = 1;
        }

        $param['historyId']   = $historyId;
        return $orderInfo;
    }

    //查询订单信心
    public function getOrderInfos(&$param){
        if(!is_array($param))
            return false;
        $historyId          = 0;
        //查询3个月之前的订单
        $orderInfo          = self::find()->where($param)->joinWith('lgistics',true,'LEFT JOIN')->asArray()->one();

        //若果没有3个月之后的订单  查询3个月之后的订单
        if(empty($orderInfo)){
            $historyId      = 1;
            $orderInfo = OrderInfoHistory::find()->where($param)->joinWith('lgistics',true,'LEFT JOIN')->asArray()->one();
        }
        $param['historyId'] = $historyId;
        return $orderInfo;
    }

    //处理查询条件
    private static function getParams($params){
        if(!is_array($params))
            return false;

        //前三个月的
        $whereArr= array();
        if(isset($params['update_time'])){
            //有状态的参数的时候
            if(isset($params['status'])){
                //设置状态的时候
                if(!array_key_exists($params['status'],OrderInfo::$STATUS_DESC))
                    return false;

                if(in_array($params['status'],self::$STATUS_IN_KEY)){
                    array_push($whereArr,array('in','status',self::$STATUS_IN_KEY));
                }else{
                    array_push($whereArr,array('in','status',$params['status']));
                }

                if($params['status'] == OrderInfo::$STATUS_ORDER_CREATED){
                    array_push($whereArr,array('between','create_time',date('Y-m-d H:i:s',strtotime("-12 hours")),date('Y-m-d H:i:s',time())));
                }
            }
                //没有设置状态的时候
            array_push($whereArr,array('between','create_time',date('Y-m-d H:i:s',$params['update_time']),date('Y-m-d H:i:s',time())));

        }else {

            if (isset($params['status'])) {
                if (!array_key_exists($params['status'], OrderInfo::$STATUS_DESC))
                    return false;

                if (in_array($params['status'], self::$STATUS_IN_KEY)) {
                    array_push($whereArr, array('in', 'status', self::$STATUS_IN_KEY));
                } else {
                    array_push($whereArr, array('in', 'status', $params['status']));
                }

                if($params['status'] == OrderInfo::$STATUS_ORDER_CREATED){
                    array_push($whereArr,array('between','create_time',date('Y-m-d H:i:s',strtotime("-12 hours")),date('Y-m-d H:i:s',time())));
                }
            }
            //处理三个月以后的订单
            array_push($whereArr, array('<', 'create_time', date('Y-m-d H:i:s', strtotime("-3 month"))));
        }
        return $whereArr;
    }

    //查询用户的订单列表
    public function getUidOrderInfo($param,$type=0){

        if(!is_array($param))
            return false;

        //如果有timesolt ：0 三个月之前的订单 ；timesolt ：1 三个月之后的订单
        if(!empty($param['update_time'])){
            $histroryId = 0;
            $modelOrderInfo = OrderInfo::find();
        } else{
            $histroryId = 1;
            $modelOrderInfo = OrderInfoHistory::find();
        }

        //当前用户的订单条件 可以将bestry_uid设置成索引
        $modelOrderInfo->onCondition(['bestry_uid'=>$param['bestry_uid']]);

        //拼接where语句
        $arrWhere = self::getParams($param);
        if(count($arrWhere) > 0){
            foreach($arrWhere as $val){
                $modelOrderInfo->andOnCondition($val);
            }
        }

        //分页
        $pages      = new Pagination(['totalCount' =>$modelOrderInfo->count(), 'pageSize' =>  $param['pagessize']]);
        $dataInfo ='';

        //$type =1查询订单信息  0 查询订单的条数
        switch($type){
            case 1:                             //根据订单号 得出订单的 商品
                $dataInfo   = $modelOrderInfo->offset(($param['pages']-1) * $pages->limit)->limit($pages->limit)->orderBy(['create_time'=>SORT_DESC])->asArray()->all();

                //处理5状态的评论
                if(count($dataInfo) >0){
                    foreach($dataInfo as $key=>&$val){
                        if(isset($param['status']) && $param['status'] == OrderInfo::$STATUS_ORDER_OK && $this->getOrderGoodsList($val['order_info_id'],$histroryId)['flg']==self::$STATUS_COMMENT_OK){
                            unset($dataInfo[$key]);
                            continue;
                        }else{
                            $val['orderGoods'] = $this->getOrderGoodsList($val['order_info_id'],$histroryId);
                        }
                    }
                }

                break;
            case 2:                             //只返回订单的数量
                $dataInfo = $modelOrderInfo->count();
                break;
        }
        return array('data'=>$dataInfo,'page'=>$pages);
    }

    //查询订单的配送信息
    public function orderInfoExpress($orderInfoId){
        if(empty($orderInfoId))
            return false;

        //处理查询条件
        $orderInfoWhere =   array('order_info_id'=>$orderInfoId);

        //查询信息
        $infoExpress    =   OrderAddress::find()->where($orderInfoWhere)->one();
        //如果订单信息为空 怎查询历史
        if(empty($infoExpress))
            $infoExpress=   OrderExpressHistory::find()->where($orderInfoWhere)->one();

        return  $infoExpress;
    }

    //处理商品的状态下的订单个数
    public function orderInfoNum($param,$stauts){
        if(!is_array($param)){
            return false;
        }

        //切换链接查询 若果时间为空则查询前三个月的 否自查询历史订单
        if(!empty($param['update_time'])){
            $historyId      = 0;
            $modelOrderInfo = OrderInfo::find();
        } else{
            $historyId      = 1;
            $modelOrderInfo = OrderInfoHistory::find();
        }

        $modelOrderInfo->onCondition(['bestry_uid'=>$param['bestry_uid']]);
        $param['status']    = $stauts;

        //拼接where语句
        $arrWhere = self::getParams($param);

        //查询相关的信息
        if(count($arrWhere) > 0){
            foreach($arrWhere as $val){
                $modelOrderInfo->andOnCondition($val);
            }
        }

        //计算待评价
        if($stauts == OrderInfo::$STATUS_ORDER_OK){
            $orderInfo = $modelOrderInfo->all();
            if(count($orderInfo) >0){
                foreach($orderInfo as $key=>$val){
                    if($stauts == OrderInfo::$STATUS_ORDER_OK && $this->getOrderGoodsList($val['order_info_id'],$historyId)['flg']==1){
                        unset($orderInfo[$key]);
                        continue;
                    }
                }
            }
            $data['num'] = count($orderInfo);
        }else{
            $data['num'] = $modelOrderInfo->count();
        }

        return $data;
    }

    //获取订单的商品
    public function getOrderGoodsList($orderInfoId,$flgs=0){

        if (empty($orderInfoId))
            return '';

        //flgs :0 前三个月的订单 flgs:1 历史订单
        if($flgs == 0)
            $orderModel = OrderGoods::find()->where(['order_info_id'=>$orderInfoId]);
        else
            $orderModel = OrderGoodsHistory::find()->where(['order_info_id'=>$orderInfoId]);

        $orderGoods     = $orderModel->select(['order_goods_id','product_id','buy_number','commented','goods_id','buy_price','try_coin'])->asArray()->all();
        if($flgs == 0)
            $countflg   = OrderGoods::find()->where(['order_info_id'=>$orderInfoId,'commented'=>0])->count();
        else
            $countflg   = OrderGoodsHistory::find()->where(['order_info_id'=>$orderInfoId,'commented'=>0])->count();

        $flg            = self::$STATUS_COMMENT_OK;
        if($countflg >0)
            $flg        = self::$STATUS_COMMENT_NO;
        //redis获取商品的图片
        if(is_array($orderGoods)){
            foreach($orderGoods as $key=>&$val){
                //判断是否是喜试还是优先   //TODO 喜事和优先区别
                $isOrNoLiketry   =Yii::$app->redis_goods->sismember('oldLiketryOrderGoodsId',$orderInfoId.'_'.$val['goods_id'].'_'.$val['product_id']);
                //取商品详情 如果是喜事的商品则加goods_id+ 2000万
                if($isOrNoLiketry)
                    $val['goodPic']  = Goods::findByGoodsIdFromRedis($val['goods_id']+self::$LIKETRY_DIFF);
                else
                    $val['goodPic']  = Goods::findByGoodsIdFromRedis($val['goods_id']);

                //取规格详情
                $val['products'] = ProductDetail::findByProductIdFromRedis($val['product_id'],['spec_desc']);

            }
        }

        $orderInfo = array('data'=>$orderGoods,'flg'=>$flg);

        return $orderInfo;
    }

    //获取商品的总数量
    public function getOrderGoodsNum($orderInfoId,$flgs=0){

        if (empty($orderInfoId))
            return '';
        if($flgs ==1){
            $orderModel = OrderGoodsHistory::find()->select(['sum(buy_number) as num'])->where(['order_info_id'=>$orderInfoId])->asArray()->one();
        }else
            $orderModel = OrderGoods::find()->select(['sum(buy_number) as num'])->where(['order_info_id'=>$orderInfoId])->asArray()->one();
        return $orderModel['num'];
    }

    //wap 获取订单
    public function getOrderWap($params){
        if(!is_array($params))
            return false;

        //查询条件

        $modelOrderInfo =  OrderInfo::find();
        $modelOrderInfo->andOnCondition(['bestry_uid'=>$params['bestry_uid']]);

        $modelOrderInfo->andOnCondition(['between','create_time',date('Y-m-d H:i:s',strtotime("-3 month")),date('Y-m-d H:i:s',time())]);
       
        $historyId      = 0;
        //前三个月的总条数
        $countOrder     =$modelOrderInfo->count();
        //$pages          = new Pagination(['totalCount' =>$modelOrderInfo->count(), 'pageSize' =>  $params['pagessize']]);

        //查询数据
        $dataInfo       = $modelOrderInfo->offset(($params['pages']-1) * $params['pagessize'])->limit($params['pagessize'])->orderBy(['create_time'=>SORT_DESC])->asArray()->all();


        //组装goods_detail详情
        if(count($dataInfo) > 0){
            foreach($dataInfo as $key=>&$val){
                $val['orderGoods'] = $this->getOrderGoodsList($val['order_info_id'],$historyId);
            }
        }


       /* //计算历史的开始
        $dataInfoHistory =array();
        if($countOrder <= $params['pagessize'] * $params['pages'] ){
            $historyId =1;
            $modelOrderInfoHistory =  OrderInfoHistory::find();
            $modelOrderInfoHistory->onCondition(['bestry_uid'=>$params['bestry_uid']]);

            //计算历史的开始
            //$pagesHistry = floor($params['pagessize'] * $params['pages'] / $countOrder);

            if($countOrder == $params['pagessize'] * $params['pages'])
                $pagesHistry=1;
            else
                $pagesHistry = ceil(($params['pagessize'] * $params['pages']-$countOrder)/$params['pagessize']);

            if($params['pagessize'] * $params['pages']-$countOrder-$params['pagessize'] ==0)
                $pagesHistry =2;

            $dataInfoHistory       = $modelOrderInfoHistory->offset(($pagesHistry-1) * $params['pagessize'])->limit($params['pagessize'])->orderBy(['create_time'=>SORT_DESC])->asArray()->all();

            if(count($dataInfoHistory) > 0){
                foreach($dataInfoHistory as $key=>&$val){
                    $val['orderGoods'] = $this->getOrderGoodsList($val['order_info_id'],$historyId);
                }
            }

        }*/

        //$dataRe = array_merge($dataInfo,$dataInfoHistory);
        //返回参数
        return ['data'=>$dataInfo];

    }
    //物流信息
    public function getLogic($delivery_code,$order_sn){

        if(empty($delivery_code))
            return false;

        if(empty($order_sn))
            return false;

        return  ExpInfo::find()->where(['expid'=>$delivery_code,'orderid'=>$order_sn])->orderBy(['fid'=>SORT_DESC])->asArray()->all();
    }

    //关系 order_info == order_express
    public function getLgistics(){
        return $this->hasOne(OrderAddress::className(), ['order_info_id' => 'order_info_id']);
    }

    //关系 order_info == order_express
    public function getManyGoods(){
        return $this->hasMany(OrderGoods::className(), ['order_info_id' => 'order_info_id']);
    }
}

